<?php
/**
 * Cache        系统核心-缓存
 * @copyright   Copyright(c) 2024-2034
 * @author      tianjie <527707665@qq.com>
 * @link        http://www.tinphp.com/
 * @version     4.1
 */

namespace tian;

class Cache
{
    //缓存扩展名
    const EXT = '.tpl';

    protected $cachePath = 'cache';

    public function __construct()
    {
        $this->cachePath = (new App())->getRuntimePath() . '/' . $this->cachePath;
    }

    /**
     * 设置文件缓存
     * @param string $key 文件名
     * @param $data
     * @return bool
     */
    public function set(string $key, $data): bool
    {
        $filename = $this->cachePath . '/' . $key . self::EXT;
        if (file_exists($filename)) {
            $res = $this->get($key);
            if (md5($res) == md5($data)) {
                return true;
            }
        }
        if (!is_dir(dirname($filename))) {
            mkdir(dirname($filename));
        }

        $source = fopen($filename, 'w+');
        fwrite($source, json_encode($data, JSON_UNESCAPED_UNICODE));
        fclose($source);

        return true;
    }

    /**
     * 获取文件缓存
     * @param string $key 文件名
     * @return mixed|string
     */
    public function get(string $key)
    {
        $filename = $this->cachePath . '/' . $key . self::EXT;
        if (!file_exists($filename)) {
            return '缓存文件已经不存在';
        } else {
            $res = file_get_contents($filename, true);
        }
        return json_decode($res, true);
    }

    /**
     * 删除文件缓存
     * @param string $key 文件名
     * @return true
     */
    public function del(string $key): bool
    {
        $filename = $this->cachePath . '/' . $key . self::EXT;
        unlink($filename);
        return true;
    }

    /**
     * 验证缓存是否存在
     * @param string $key 文件名
     * @return bool
     */
    public function has(string $key): bool
    {
        $filename = $this->cachePath . '/' . $key . self::EXT;
        if (file_exists($filename)) {
            return true;
        }
        return false;
    }

}

